package jobhunter.security;


import jobhunter.model.User;
import jobhunter.repository.UserRepository;
import jobhunter.tool.ContextUtil;
/**
 * Holds the security related information during request execution.
 */

public  class SecurityContext {


    private static ThreadLocal<User> user = new ThreadLocal<User>();    // Lazyly retrieved from the DB if needed (if getUser() is called).
    private static ThreadLocal<Long> userId = new ThreadLocal<Long>();  // retrieved in from the session. Non null <=> user logged in.

    public static User getUser()  
    {       
        if (getUserId() == null) 
        {  
            return null;
        }
        
        if (user.get() == null) 
        {  // User not loaded yet.
            User user = ((UserRepository) ContextUtil.getSpringBean(UserRepository.class)).findById(getUserId());
            setUser( user );  // Lazy loading if needed.
        }

        return user.get();
    }


    private static  void setUser(User userParam) {
        //Security constraint
        if (user.get() != null)
        {
            throw new IllegalStateException("Bug: Could not set a new user on the security context once a user has already been set");
        }
        if (userId.get() == null)
        {
            userId.set(userParam.getId());
        }
        user.set(userParam);
    } 

    //method to know if the user is logged or not
    public static boolean isUserLoggedIn() 
    {
		return getUserId() != null;
    }


    //get the value of the threadlocal userId 
    public static  Long getUserId() 
    {
       if (userId.get() == null) 
       { // Then try to get it from the HttpSession.   
    	   
    	  // Long id = (Long)ContextUtil.getHttpSession().getAttribute("UserId");
    	   
    	   
    	   SecurityService loginService = (SecurityService) ContextUtil.getSpringBean(SecurityService.class);
    	   Long id = loginService.getLoggedInUserIdFromSession(); 
         
           if (id != null) 
           {  // A user is effectively logged in.
                userId.set(id);  // remember it in the SecurityContext.
           }
        }
       
        return userId.get();
    }
    public static void clear() {
        user.set(null);
        userId.set(null);
    }

}
